<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-select v-model="formData.protocol" placeholder="请选择协议" style="width: 100%">
                  <el-option label="FTP" value="ftp" />
                  <el-option label="SFTP" value="sftp" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主机地址" prop="host">
                <el-input v-model="formData.host" placeholder="请输入服务器地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口" prop="port">
                <el-input-number
                  v-model="formData.port"
                  :min="1"
                  :max="65535"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="formData.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="formData.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="连接超时(秒)" prop="timeout">
            <el-input-number
              v-model="formData.timeout"
              :min="1"
              :max="60"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <!-- SFTP特有配置 -->
          <template v-if="formData.protocol === 'sftp'">
            <el-form-item label="私钥认证" prop="usePrivateKey">
              <el-switch v-model="formData.usePrivateKey" />
            </el-form-item>

            <template v-if="formData.usePrivateKey">
              <el-form-item label="私钥文件" prop="privateKey">
                <el-input
                  v-model="formData.privateKey"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入私钥内容"
                />
              </el-form-item>
              <el-form-item label="私钥密码" prop="privateKeyPassphrase">
                <el-input
                  v-model="formData.privateKeyPassphrase"
                  type="password"
                  placeholder="请输入私钥密码（可选）"
                  show-password
                />
              </el-form-item>
            </template>
          </template>

          <!-- FTP特有配置 -->
          <template v-else>
            <el-form-item label="传输模式" prop="ftpMode">
              <el-radio-group v-model="formData.ftpMode">
                <el-radio label="active">主动模式</el-radio>
                <el-radio label="passive">被动模式</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="编码格式" prop="encoding">
              <el-select v-model="formData.encoding" placeholder="请选择编码" style="width: 100%">
                <el-option label="UTF-8" value="utf8" />
                <el-option label="GBK" value="gbk" />
                <el-option label="ISO-8859-1" value="latin1" />
              </el-select>
            </el-form-item>
          </template>
        </el-tab-pane>

        <!-- 文件配置 -->
        <el-tab-pane label="文件配置" name="fileConfig">
          <el-form-item label="根目录" prop="rootPath">
            <el-input
              v-model="formData.rootPath"
              placeholder="请输入根目录路径，例如: /data/ftp"
            />
            <span class="el-form-item__tip">文件操作将基于此目录进行</span>
          </el-form-item>

          <el-form-item label="文件匹配模式" prop="filePattern">
            <el-input
              v-model="formData.filePattern"
              placeholder="例如: *.csv 或 data_*.txt"
            />
            <span class="el-form-item__tip">支持通配符 * 和 ?</span>
          </el-form-item>

          <el-form-item label="递归搜索" prop="recursive">
            <el-switch v-model="formData.recursive" />
            <span class="el-form-item__tip">是否搜索子目录中的文件</span>
          </el-form-item>

          <el-form-item label="文件排序" prop="fileSort">
            <el-select v-model="formData.fileSort" placeholder="请选择文件排序方式" style="width: 100%">
              <el-option label="按文件名升序" value="name_asc" />
              <el-option label="按文件名降序" value="name_desc" />
              <el-option label="按修改时间升序" value="mtime_asc" />
              <el-option label="按修改时间降序" value="mtime_desc" />
              <el-option label="按文件大小升序" value="size_asc" />
              <el-option label="按文件大小降序" value="size_desc" />
            </el-select>
          </el-form-item>

          <el-form-item label="文件过滤" prop="fileFilterEnabled">
            <el-switch v-model="formData.fileFilterEnabled" />
          </el-form-item>

          <template v-if="formData.fileFilterEnabled">
            <el-form-item label="最小文件大小(KB)" prop="minFileSize">
              <el-input-number
                v-model="formData.minFileSize"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="最大文件大小(KB)" prop="maxFileSize">
              <el-input-number
                v-model="formData.maxFileSize"
                :min="formData.minFileSize"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="时间范围" prop="timeRangeEnabled">
              <el-switch v-model="formData.timeRangeEnabled" />
            </el-form-item>
            <template v-if="formData.timeRangeEnabled">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                      v-model="formData.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                      v-model="formData.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </template>
        </el-tab-pane>

        <!-- 采集配置 -->
        <el-tab-pane label="采集配置" name="collection">
          <el-form-item label="采集模式" prop="collection.mode">
            <el-radio-group v-model="formData.collection.mode">
              <el-radio label="once">一次性采集</el-radio>
              <el-radio label="scheduled">定时采集</el-radio>
              <el-radio label="watch">文件监视</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="formData.collection.mode === 'scheduled'">
            <el-form-item label="采集频率" prop="collection.cron">
              <el-select
                v-model="formData.collection.cron"
                placeholder="请选择采集频率"
                style="width: 100%"
              >
                <el-option label="每小时" value="0 0 * * * ?" />
                <el-option label="每天" value="0 0 0 * * ?" />
                <el-option label="每周" value="0 0 0 ? * MON" />
                <el-option label="每月" value="0 0 0 1 * ?" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>

            <template v-if="formData.collection.cron === 'custom'">
              <el-form-item label="CRON表达式" prop="collection.customCron">
                <el-input
                  v-model="formData.collection.customCron"
                  placeholder="请输入CRON表达式"
                />
                <span class="el-form-item__tip">例如: 0 0/30 * * * ? 表示每30分钟执行一次</span>
              </el-form-item>
            </template>
          </template>

          <template v-else-if="formData.collection.mode === 'watch'">
            <el-form-item label="监视间隔(秒)" prop="collection.watchInterval">
              <el-input-number
                v-model="formData.collection.watchInterval"
                :min="10"
                :max="3600"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </template>

          <el-form-item label="文件处理方式" prop="collection.fileAction">
            <el-select
              v-model="formData.collection.fileAction"
              placeholder="请选择文件处理方式"
              style="width: 100%"
            >
              <el-option label="仅读取" value="read" />
              <el-option label="读取后移动" value="move" />
              <el-option label="读取后删除" value="delete" />
              <el-option label="读取后重命名" value="rename" />
            </el-select>
          </el-form-item>

          <template v-if="formData.collection.fileAction === 'move'">
            <el-form-item label="移动目录" prop="collection.movePath">
              <el-input
                v-model="formData.collection.movePath"
                placeholder="请输入移动目标目录"
              />
            </el-form-item>
          </template>

          <template v-else-if="formData.collection.fileAction === 'rename'">
            <el-form-item label="重命名模式" prop="collection.renamePattern">
              <el-input
                v-model="formData.collection.renamePattern"
                placeholder="例如: processed_{filename}"
              />
              <span class="el-form-item__tip">可用变量: {filename}, {date}, {time}, {timestamp}</span>
            </el-form-item>
          </template>

          <el-form-item label="文件编码" prop="collection.fileEncoding">
            <el-select
              v-model="formData.collection.fileEncoding"
              placeholder="请选择文件编码"
              style="width: 100%"
            >
              <el-option label="UTF-8" value="utf8" />
              <el-option label="GBK" value="gbk" />
              <el-option label="GB2312" value="gb2312" />
              <el-option label="ISO-8859-1" value="latin1" />
            </el-select>
          </el-form-item>

          <el-form-item label="批量大小" prop="collection.batchSize">
            <el-input-number
              v-model="formData.collection.batchSize"
              :min="1"
              :max="1000"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">每次采集的最大文件数量</span>
          </el-form-item>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-form-item label="断点续传" prop="advanced.resumeEnabled">
            <el-switch v-model="formData.advanced.resumeEnabled" />
            <span class="el-form-item__tip">支持从上次中断的位置继续传输</span>
          </el-form-item>

          <el-form-item label="校验文件完整性" prop="advanced.verifyChecksum">
            <el-switch v-model="formData.advanced.verifyChecksum" />
          </el-form-item>

          <template v-if="formData.advanced.verifyChecksum">
            <el-form-item label="校验算法" prop="advanced.checksumAlgorithm">
              <el-select
                v-model="formData.advanced.checksumAlgorithm"
                placeholder="请选择校验算法"
                style="width: 100%"
              >
                <el-option label="MD5" value="md5" />
                <el-option label="SHA-1" value="sha1" />
                <el-option label="SHA-256" value="sha256" />
                <el-option label="CRC32" value="crc32" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="错误处理" prop="advanced.errorHandling">
            <el-select
              v-model="formData.advanced.errorHandling"
              placeholder="请选择错误处理策略"
              style="width: 100%"
            >
              <el-option label="跳过错误继续执行" value="skip" />
              <el-option label="停止采集并报错" value="stop" />
              <el-option label="重试3次后跳过" value="retry" />
            </el-select>
          </el-form-item>

          <el-form-item label="重试配置" prop="advanced.retryEnabled">
            <el-switch v-model="formData.advanced.retryEnabled" />
          </el-form-item>

          <template v-if="formData.advanced.retryEnabled">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大重试次数" prop="advanced.maxRetries">
                  <el-input-number
                    v-model="formData.advanced.maxRetries"
                    :min="1"
                    :max="10"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="重试间隔(秒)" prop="advanced.retryInterval">
                  <el-input-number
                    v-model="formData.advanced.retryInterval"
                    :min="1"
                    :max="60"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <el-form-item label="自定义脚本" prop="advanced.customScript">
            <el-input
              v-model="formData.advanced.customScript"
              type="textarea"
              :rows="5"
              placeholder="可输入JavaScript脚本进行自定义处理"
            />
            <span class="el-form-item__tip">可用于文件过滤、内容转换等高级处理</span>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button type="success" @click="testConnection">测试连接</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditFtpDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit', 'test-connection'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑FTP/SFTP数据源' : '新增FTP/SFTP数据源'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      protocol: 'ftp',
      host: '',
      port: 21,
      username: '',
      password: '',
      timeout: 30,
      // SFTP特有
      usePrivateKey: false,
      privateKey: '',
      privateKeyPassphrase: '',
      // FTP特有
      ftpMode: 'passive',
      encoding: 'utf8',
      // 文件配置
      rootPath: '/',
      filePattern: '*',
      recursive: false,
      fileSort: 'name_asc',
      fileFilterEnabled: false,
      minFileSize: 0,
      maxFileSize: 10240,
      timeRangeEnabled: false,
      startTime: '',
      endTime: '',
      // 采集配置
      collection: {
        mode: 'once',
        cron: '0 0 * * * ?',
        customCron: '',
        watchInterval: 60,
        fileAction: 'read',
        movePath: '',
        renamePattern: 'processed_{filename}',
        fileEncoding: 'utf8',
        batchSize: 10
      },
      // 高级配置
      advanced: {
        resumeEnabled: true,
        verifyChecksum: false,
        checksumAlgorithm: 'md5',
        errorHandling: 'retry',
        retryEnabled: true,
        maxRetries: 3,
        retryInterval: 5,
        customScript: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      host: [
        { required: true, message: '请输入主机地址', trigger: 'blur' }
      ],
      port: [
        { required: true, message: '请输入端口号', trigger: 'blur' }
      ],
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      privateKey: [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.protocol === 'sftp' && formData.value.usePrivateKey && !value) {
              return callback(new Error('请输入私钥内容'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      rootPath: [
        { required: true, message: '请输入根目录路径', trigger: 'blur' }
      ],
      'collection.movePath': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.collection.fileAction === 'move' && !value) {
              return callback(new Error('请输入移动目录路径'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'collection.customCron': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.collection.mode === 'scheduled' && 
                formData.value.collection.cron === 'custom' && 
                !value) {
              return callback(new Error('请输入CRON表达式'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ]
    }

    // 测试连接
    const testConnection = async () => {
      try {
        await formRef.value.validate()
        
        const config = {
          protocol: formData.value.protocol,
          host: formData.value.host,
          port: formData.value.port,
          username: formData.value.username,
          password: formData.value.password,
          timeout: formData.value.timeout
        }

        if (formData.value.protocol === 'sftp' && formData.value.usePrivateKey) {
          config.privateKey = formData.value.privateKey
          config.privateKeyPassphrase = formData.value.privateKeyPassphrase
        }

        emit('test-connection', config)
      } catch (error) {
        console.error('连接测试验证失败:', error)
        ElMessage.error('请检查连接配置是否正确')
      }
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理自定义CRON表达式
        const finalData = JSON.parse(JSON.stringify(formData.value))
        if (finalData.collection.cron === 'custom') {
          finalData.collection.cron = finalData.collection.customCron
        }
        delete finalData.collection.customCron
        
        // 清理未使用的配置
        if (finalData.protocol !== 'sftp') {
          delete finalData.usePrivateKey
          delete finalData.privateKey
          delete finalData.privateKeyPassphrase
        }
        if (finalData.protocol !== 'ftp') {
          delete finalData.ftpMode
          delete finalData.encoding
        }
        if (!finalData.fileFilterEnabled) {
          delete finalData.minFileSize
          delete finalData.maxFileSize
          delete finalData.timeRangeEnabled
          delete finalData.startTime
          delete finalData.endTime
        }
        if (!finalData.advanced.retryEnabled) {
          delete finalData.advanced.maxRetries
          delete finalData.advanced.retryInterval
        }
        if (!finalData.advanced.verifyChecksum) {
          delete finalData.advanced.checksumAlgorithm
        }
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          collection: {
            ...defaultFormData.collection,
            ...(newVal.collection || {})
          },
          advanced: {
            ...defaultFormData.advanced,
            ...(newVal.advanced || {})
          }
        }))
        
        // 处理自定义CRON表达式
        if (newVal.collection?.cron && 
            !['0 0 * * * ?', '0 0 0 * * ?', '0 0 0 ? * MON', '0 0 0 1 * ?'].includes(newVal.collection.cron)) {
          formData.value.collection.cron = 'custom'
          formData.value.collection.customCron = newVal.collection.cron
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      testConnection,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>